package org.huoran.sakamichi.main.netty.webSocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ServerManager implements InitializingBean,DisposableBean {

    private String port;
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    public ServerManager(String port){
        this.port = port;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Thread thread = new Thread(new WebSocketServerTask());
        thread.start();
    }

    @Override
    public void destroy() throws Exception {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    /**
     * 初始化websocket服务端
     * @throws Exception
     */
    public void init() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketChannelInitializer())
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        System.out.println("webSocket server start with port : " + port);
        ChannelFuture channelFuture = bootstrap.bind(Integer.parseInt(port)).sync();
        channelFuture.channel().closeFuture().sync();
    }

    /**
     * 子线程启动websocket服务端
     */
    private class WebSocketServerTask implements Runnable {
        @Override
        public void run(){
            try {
                init();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
